#include "comm.hpp"

Init it;

int main()
{
    // 1.创建公共的key
    key_t key = ftok(FILENAME, PROJ_ID);
    if (key == -1)
    {
        Log("creat key fail", Error) << "client_key: " << key << std::endl;
        return 1;
    }
    Log("creat key success", Debug) << "client_key: " << key << std::endl;
    sleep(1);

    // 2.创建共享内存
    int shmid = shmget(key, SHM_SIZE, IPC_CREAT | IPC_EXCL | 0666);
    if (shmid == -1)
    {
        Log("creat shmid fail", Error) << "client_shmid: " << shmid << std::endl;
        return 2;
    }
    Log("creat shmid success", Debug) << "client_shmid: " << shmid << std::endl;
    sleep(1);

    // 3.将共享内存挂到地址空间
    char* shmem = (char*)shmat(shmid, nullptr, 0);
    if (shmem == nullptr)
    {
        Log("creat shared memory fail", Error) << "client_shmid: " << shmid << std::endl;
        return 3;
    }
    Log("creat shared memory success", Debug) << "client_shmid: " << shmid << std::endl;
    sleep(1);

    // 4.使用共享内存
    int fd = OpenFile(O_RDONLY);
    while (true)
    {
        Wait(fd);

        printf("%s\n", shmem);
        if (strcmp(shmem, "quit") == 0)
            break;
    }

    // 5.将共享内存和进程去关联
    int n = shmdt(shmem);
    assert(n != -1);
    (void)n;
    Log("unlink shared memory success", Debug) << "client_shmid: " << shmid << std::endl;
    

    // 6.删除共享内存
    n = shmctl(shmid, IPC_RMID, nullptr);
    assert(n != -1);
    (void)n;
    Log("delete shared memory success", Debug) << "client_shmid: " << shmid << std::endl;


    return 0;
}